package com.jjyu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjyu.dao.OrderMapper;
import com.jjyu.entity.Inventory;
import com.jjyu.entity.Order;
import com.jjyu.entity.OrderItem;
import com.jjyu.entity.User;
import com.jjyu.exception.InsufficientStockException;
import com.jjyu.exception.UserNotFoundException;
import com.jjyu.service.InventoryService;
import com.jjyu.service.OrderItemService;
import com.jjyu.service.OrderService;
import com.jjyu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private UserService userService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemService orderItemService;
    /**
     *   a. 检查用户是否存在。
     *   b. 验证餐品库存是否充足并扣除库存。
     *   c. 计算订单总金额。
     *   d. 创建订单记录。
     * @param userId user的ID
     * @param orderItems 食物的ID，数量
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createOrder(Integer userId, HashMap<Integer, Integer> orderItems) {
        double totalPrice=0;//计算订单总金额
        List<String> outOfStockItems=new ArrayList<>();//记录缺货商品
        Inventory inventory;//库存
        int requestedQuantity;//请求数量
        int availableQuantity;//可用数量

        //检查用户是否存在
        User user=userService.getById(userId);
        if(user==null) {
            throw new UserNotFoundException("用户不存在,ID:"+userId);
        }


        //创建订单 orderId,userId,totalAmount;
        Order order=new Order();
        orderMapper.insert(order); // 先插入以生成ID
        Integer orderId=order.getOrderId();// 获取生成的订单ID
        order.setUserId(userId);

        //b. 验证餐品库存是否充足并扣除库存。
        for(Integer orderItemId:orderItems.keySet()){
            inventory=inventoryService.getById(orderItemId);
            availableQuantity=inventory.getQuantity();
            requestedQuantity=orderItems.get(orderItemId);

            boolean isAcceptPartialOrder=new Random().nextBoolean();//模拟用户是否同意部分下单
            if(availableQuantity<requestedQuantity)
            {
                if(!isAcceptPartialOrder){//用户不同意部分下单
                    throw new InsufficientStockException(inventory.getItemName()+"库存数量不足：请求数量"+requestedQuantity+ "，可用数量"+
                            availableQuantity);
                }
                //用户同意，则部分下单
                requestedQuantity=availableQuantity;
                outOfStockItems.add(inventory.getItemName());
            }
            //累加订单项金额
            totalPrice+=requestedQuantity*inventory.getPrice();
            //扣减库存
            inventory.setQuantity(availableQuantity-requestedQuantity);
            inventoryService.updateById(inventory);//更新库存

            //创建订单项 orderItemId,orderId,restaurantId,itemName,quantity,price;
            OrderItem orderItem=new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setRestaurantId(inventory.getRestaurantId());
            orderItem.setItemName(inventory.getItemName());
            orderItem.setQuantity(requestedQuantity);
            orderItem.setPrice(BigDecimal.valueOf(inventory.getPrice()*requestedQuantity));
            orderItemService.save(orderItem);
        }
        order.setTotalAmount(BigDecimal.valueOf(totalPrice));
        orderMapper.updateById(order);// 更新订单以设置总金额

        //输出缺货商品
        if(!outOfStockItems.isEmpty()){
            System.out.println("部分订单项缺货："+String.join(",",outOfStockItems));
        }
        return true;
    }

}
